package com.ruoyi.web.controller.mobile;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.properties.RsaKeyProperties;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.util.RsaUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mobile.company.domain.vo.*;
import com.ruoyi.mobile.user.domain.vo.SendCodeValidateVO;
import com.ruoyi.mobile.user.domain.vo.UserVO;
import com.ruoyi.sms.service.DynamicMessageService;
import com.ruoyi.system.domain.CompanyInfo;
import com.ruoyi.system.dto.register.RegisterDto;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.MobileUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/h5/company")
@Api(tags = "【新】H5企业相关接口")
public class CompanyController extends BaseController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private MobileUserServiceImpl userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private DynamicMessageService smsService;

    @ApiOperation("企业登录")
    @PostMapping("/login")
    public AjaxResult<Map<String, Object>>  login(@RequestBody CompanyLoginVO companyLoginVO){
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.TOKEN, loginService.login_h5_company(companyLoginVO));
        return AjaxResult.success(map);
    }

    @ApiOperation("查询当前企业信息")
    @GetMapping("/one")
    public AjaxResult<CompanyVO> getOne(){
        CompanyVO userVO=userService.getCompanyOne();
        return AjaxResult.success(userVO);
    }

    @ApiOperation("查询当前企业信息详情")
    @GetMapping("/one_desc")
    public AjaxResult<CompanyInfo> getOneDesc(){
        CompanyInfo userVO=userService.getCompanyOnDesc();
        return AjaxResult.success(userVO);
    }

    @ApiOperation("退出登录")
    @PostMapping("/login_out")
    public AjaxResult<String> loginOut(HttpServletRequest request, HttpServletResponse response){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
        return AjaxResult.success();
    }


    @ApiOperation("注册企业信息")
    @PostMapping("/register")
    public AjaxResult<CompanyInfo> register(@RequestBody CompanyAddVO companyAddVO) throws Exception {
        return userService.registerCompany(companyAddVO);
    }

    @ApiOperation("认证企业信息")
    @PostMapping("/authentication")
    public AjaxResult<CompanyInfo> authentication(@RequestBody CompanyAuthenticationVO companyAuthenticationVO) throws Exception {
        return userService.authentication(companyAuthenticationVO);
    }



    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    @ApiOperation("更新企业密码")
    @PostMapping("/update_password")
    public AjaxResult<String> updateCompanyPasswordVO(@RequestBody UpdateCompanyPasswordVO passwordVO) throws Exception {

        PrivateKey privateKey = rsaKeyProperties.getPrivateKey();

        if(StringUtils.isBlank(passwordVO.getPassword())){
            throw new ServerException("新密码不能为空");
        }
        passwordVO.setPassword(RsaUtils.decrypt(passwordVO.getPassword(), privateKey));

        userService.updateCompanyPasswordVO(passwordVO);
        return AjaxResult.success();
    }


    @ApiOperation("找回密码-验证企业信用代码")
    @PostMapping("/validate_company_code")
    public AjaxResult<CompanyInfo> validate_company_code(@RequestBody CompanyValidateCodeVO validateCodeVO){
        return userService.validate_company_code(validateCodeVO.getUnifiedSocialCreditCode());

    }


    public static void main(String[] args) {
        System.out.println(URLUtil.encode("测试"));
    }
    @ApiOperation("发送短信")
    @PostMapping("/send_code")
    public AjaxResult<String> send_code(@ApiParam(value = "参数")  @RequestBody CompanySendCodeVO sendCodeVO){

        String code= RandomUtil.randomNumbers(4);
        logger.info(sendCodeVO.getPhone()+":::::发送短信验证码::::"+code);
        redisCache.setCacheObject(CacheConstants.CAPTCHA_CODE_KEY +"_"+sendCodeVO.getPhone()+"_"+sendCodeVO.getSmsType(),code,60*30, TimeUnit.SECONDS);
        try{

            switch (sendCodeVO.getSmsType()){
                case 1:
                    smsService.sendDynamicMessage("【光影重庆】您好，您此次验证码为:"+code+"，请不要把验证码泄漏给其他人，如非本人请勿操作。",sendCodeVO.getPhone());
                    break;
                case 2:
                    smsService.sendDynamicMessage("【光影重庆】您正在找回密码，验证码为："+code+"，请不要把验证码泄露给其他人。如非本人操作，可不用理会！",sendCodeVO.getPhone());
                    break;
            }

        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.success(code);
        }
        return AjaxResult.success();
    }


    @ApiOperation("验证短信验证码")
    @PostMapping("/validate_code")
    public AjaxResult<String> validate_code(@ApiParam(value = "参数")  @RequestBody SendCodeValidateVO validateVO)  {
        String code= redisCache.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY +"_"+validateVO.getPhone()+"_"+validateVO.getSmsType());
        if(StringUtils.isEmpty(code)){
            AjaxResult.error("短信验证码不正确或已失效!");
        }
        redisCache.deleteObject(CacheConstants.CAPTCHA_CODE_KEY +"_"+validateVO.getPhone()+"_"+validateVO.getSmsType());
        return AjaxResult.success();
    }

    @ApiOperation("验证企业信息是否认证中")
    @PostMapping("/validate_company")
    public AjaxResult<String> validate_company(@ApiParam(value = "参数")  @RequestBody CompanyValidateVO validateVO)  {
        userService.validateCompany(validateVO);
        return AjaxResult.success();
    }

    @ApiOperation("验证企业信息是否认证成功")
    @PostMapping("/validate_company_state")
    public AjaxResult<String> validate_company_state(@ApiParam(value = "参数")  @RequestBody CompanyValidateVO validateVO)  {
        userService.validateCompanyState(validateVO);
        return AjaxResult.success();
    }


}
